package com.bocai.kelala.ui.travel.stroke.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.MessageEvent;
import com.bocai.kelala.bean.MyGradOrderBean;
import com.bocai.kelala.bean.MyPublishStrokeBean;
import com.bocai.kelala.bean.OrderDetailBean;
import com.bocai.kelala.pay.alipay.AlipayApi;
import com.bocai.kelala.pay.simcpux.WxPayApi;
import com.bocai.kelala.ui.travel.main.act.MainActivity;
import com.bocai.kelala.ui.travel.stroke.contract.MyStrokeContract;
import com.bocai.kelala.ui.travel.stroke.module.MyStrokeModule;
import com.bocai.kelala.ui.travel.stroke.presenter.MyStrokePresenter;
import com.bocai.kelala.widget.PayPopupWindow;
import com.bocai.kelala.widget.SingleAlertDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuanfei on 2017/6/13.
 */

public class MyStrokeDetailActivity extends BaseActivity implements MyStrokeContract.view ,View.OnClickListener{
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_outset_date)
    TextView tvOutsetDate;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.btn_cancle)
    Button btnCancle;
    @BindView(R.id.tv_other_name)
    TextView tvOtherName;
    @BindView(R.id.btn_select)
    TextView btnSelect;
    @BindView(R.id.tv_other_phone)
    TextView tvOtherPhone;
    @BindView(R.id.ll_other_user)
    LinearLayout llOtherUser;
    @BindView(R.id.tv_start_address)
    TextView tvStartAddress;
    @BindView(R.id.tv_end_address)
    TextView tvEndAddress;
    @BindView(R.id.tv_order_information)
    TextView tvOrderInformation;
    @BindView(R.id.tv_information)
    TextView tvInformation;
    @BindView(R.id.ll_no_information)
    LinearLayout llNoInformation;
    @BindView(R.id.tv_car_information)
    TextView tvCarInformation;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_car_age)
    TextView tvCarAge;
    @BindView(R.id.tv_car_name)
    TextView tvCarName;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.ll_wait_outset)
    LinearLayout llWaitOutset;
    @BindView(R.id.ll_you_information)
    LinearLayout llYouInformation;
    @BindView(R.id.ll_car_money)
    LinearLayout llCarMoney;
    @BindView(R.id.btn_cancle1)
    Button btnCancle1;
    @BindView(R.id.btn_pay)
    Button btnPay;
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    private String orderId ;
    @Inject
    MyStrokePresenter presenter;
    private int index = 0;
    PayPopupWindow payPopupWindow;
    private String phone;


    @Override
    public int getLayoutId() {
        return R.layout.act_my_stroke_detail;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new MyStrokeModule(this)).inject(this);
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        orderId = getIntent().getStringExtra("orderId");
        initToolbar("我的行程");
        initBack(imgBack,llBack);
        presenter.orderDetail(orderId);
        btnPay.setOnClickListener(this);
        btnCancle1.setOnClickListener(this);
        btnCancle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_pay:
                backgroundAlpha(0.5f);
                payPopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.btn_cancle1:
                setDialog();
                break;
            case R.id.btn_cancle:
                if (index == 4){
                    checkReadPermission();

                }else {
                    setDialog();
                }
                break;
            case R.id.btn_confirm_pay:
//                AlipayApi alipayApi = new AlipayApi(this);
//                alipayApi.payV2();
                if (payPopupWindow.getPayType() == 0) {
                    presenter.orderPay("alipayagency",orderId);
                }else {
                    presenter.orderPay("weixinagency",orderId);
                }
                break;
        }
    }

    public void setCallPhone(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:"+phone));
        startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkReadPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 222);
        } else {
            setCallPhone();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
         if (requestCode == 222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setCallPhone();
            } else {
                showErrorTip("权限被禁止，请在设置中打开权限");
            }
        }
    }

    @Override
    public void myStrokePublish(MyPublishStrokeBean bean) {

    }

    @Override
    public void myGradOrder(MyGradOrderBean bean) {

    }

    @Override
    public void getOrderDetail(OrderDetailBean bean) {
        tvStartAddress.setText(bean.getOriginCity());
        tvEndAddress.setText(bean.getArriveCity());
        tvOutsetDate.setText(bean.getAppointTime());
        tvCarNum.setText(bean.getApplySeats()+"座");
        tvMoney.setText(bean.getPrice()+"");
        phone = bean.getDriverPhone();

        if (bean.getOrderStatus() == 0) {//待接单
            index = 0;
            llOtherUser.setVisibility(View.GONE);
            tvOrderInformation.setText("接单信息");
            tvInformation.setText("暂无车辆或车队接单");
            llNoInformation.setVisibility(View.VISIBLE);
            llYouInformation.setVisibility(View.GONE);
            llCarMoney.setVisibility(View.VISIBLE);
            llWaitOutset.setVisibility(View.GONE);
            llPay.setVisibility(View.GONE);
            btnCancle.setVisibility(View.VISIBLE);
            btnCancle.setText("取消用车");
        }else if (bean.getOrderStatus() == 1&&bean.getOrderMemberType() == 2){
            index = 1;
            llOtherUser.setVisibility(View.GONE);
            tvOrderInformation.setText("接单车队信息");
            tvInformation.setText("xxxx车队已接单 付款后查看详细信息");
            llNoInformation.setVisibility(View.VISIBLE);
            llYouInformation.setVisibility(View.GONE);
            llCarMoney.setVisibility(View.VISIBLE);
            llWaitOutset.setVisibility(View.GONE);
            llPay.setVisibility(View.VISIBLE);
            btnCancle.setVisibility(View.GONE);
            payPopupWindow = new PayPopupWindow(this,bean.getPrice()+"",this);
            payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
        }else if (bean.getOrderStatus() == 1&&bean.getOrderMemberType() == 3){
            index = 2;
            llOtherUser.setVisibility(View.GONE);
            tvOrderInformation.setText("接单信息");
            tvInformation.setText("司机已接单 付款后查看详细信息");
            llNoInformation.setVisibility(View.VISIBLE);
            llYouInformation.setVisibility(View.GONE);
            llCarMoney.setVisibility(View.VISIBLE);
            llWaitOutset.setVisibility(View.GONE);
            llPay.setVisibility(View.VISIBLE);
            btnCancle.setVisibility(View.GONE);
            payPopupWindow = new PayPopupWindow(this,bean.getPrice()+"",this);
            payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
        }else if (bean.getOrderStatus() == 2&& TextUtils.isEmpty(bean.getDriver())){
            index = 3;
            llOtherUser.setVisibility(View.VISIBLE);
            tvOrderInformation.setText("接单信息");
            tvInformation.setText("车队正在派车，请稍后");
            llNoInformation.setVisibility(View.VISIBLE);
            llYouInformation.setVisibility(View.GONE);
            llCarMoney.setVisibility(View.GONE);
            llWaitOutset.setVisibility(View.VISIBLE);
            llPay.setVisibility(View.GONE);
            btnCancle.setVisibility(View.GONE);
            tvOtherName.setText(bean.getOrderMemberName());
            tvOtherPhone.setText("联系电话  "+bean.getOrderMemberPhone());
        }else if ((bean.getOrderStatus() == 2||bean.getOrderStatus() == 5)&&!TextUtils.isEmpty(bean.getDriver())){
            index = 4;
            llOtherUser.setVisibility(View.VISIBLE);
            tvOrderInformation.setText("接单信息");
            llNoInformation.setVisibility(View.GONE);
            llYouInformation.setVisibility(View.VISIBLE);
            llCarMoney.setVisibility(View.GONE);
            llWaitOutset.setVisibility(View.VISIBLE);
            llPay.setVisibility(View.GONE);
            btnCancle.setVisibility(View.VISIBLE);
            btnCancle.setText("联系司机");
            tvOtherName.setText(bean.getOrderMemberName());
            tvOtherPhone.setText("联系电话  "+bean.getOrderMemberPhone());
//            tvCarInformation.setText(bean.getCarSeats()+"座大客车准点抵达目的地"+bean.getArriveCity());
            if (bean.getOrderStatus() == 5){
                tvCarInformation.setText(bean.getCarSeats()+"座大客车准点抵达目的地"+bean.getArriveCity());
            }else {
                tvCarInformation.setText("请及时联系司机，告知具体接送信息");
            }
            tvNum.setText(bean.getCarSeats()+"人");
            tvCarAge.setText(bean.getCarAge()+"年");
            tvCarName.setText(bean.getDriver());
            tvUserPhone.setText(bean.getDriverPhone());
        }else {
            index = 5;
            llOtherUser.setVisibility(View.VISIBLE);
            tvOrderInformation.setText("接单信息");
            llNoInformation.setVisibility(View.GONE);
            llYouInformation.setVisibility(View.VISIBLE);
            llCarMoney.setVisibility(View.GONE);
            llWaitOutset.setVisibility(View.GONE);
            llPay.setVisibility(View.GONE);
            btnCancle.setVisibility(View.GONE);
            btnCancle.setText("查看车辆证件");
        }
        if (bean.getCarSeats()!=0){
            tvNum.setText(bean.getCarSeats()+"人");
        }
    }

    @Override
    public void orderPaySuccess(String result) {
        if (payPopupWindow.getPayType() == 0) {
            AlipayApi alipayApi = new AlipayApi(this);
            alipayApi.payV2(result);
        }else {
            WxPayApi wxPayApi = new WxPayApi(this);
            wxPayApi.pay(result);
        }
//        showErrorTip("支付成功");
//        presenter.orderDetail(orderId);
        payPopupWindow.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if ("11".equals(event.msg)){
            presenter.orderDetail(orderId);
        }
    }

    @Override
    public void cancelOrderSuccess() {
        showErrorTip("取消成功");
        finish();
    }

    @Override
    public void addDepartTimeSuccess() {

    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {

        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
        showShortToast(msg);
    }
    public void setDialog(){
        new SingleAlertDialog(mContext).builder().setTitle("您确定取消用车？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presenter.cancelOrder(orderId);
                    }
                }).setNegativeButton("点错了", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
